package StudyCode.summary.csv;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ReadCSVFile {
	public static void main(String[] args) {
		List<List<String>> lists = readCSVFile("E:/Copy/csv.csv", "utf-8");
		for (List<String> list : lists) {
			System.out.println(list.toString());
		}
	}

	public static List<List<String>> readCSVFile(String f,
	                                             String charsetName) {
		InputStreamReader fr = null;
		BufferedReader br = null;

		String rec = null;
		String str;
		List<List<String>> listFile = new ArrayList<List<String>>();
		try {
			fr = new InputStreamReader(new FileInputStream(f), charsetName);
			br = new BufferedReader(fr);
			//
			while ((rec = br.readLine()) != null) {
				rec += ",";
				Pattern pCells = Pattern
						.compile("(\"[^\"]*(\"{2})*[^\"]*\")*[^,]*,");
				Matcher mCells = pCells.matcher(rec);
				List<String> cells = new ArrayList<String>();// ?list
				while (mCells.find()) {
					str = mCells.group();
					str = str.replaceAll(
							"(?sm)\"?([^\"]*(\"{2})*[^\"]*)\"?.*,", "$1");
					str = str.replaceAll("(?sm)(\"(\"))", "$2");
					cells.add(str);
				}
				listFile.add(cells);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
				}
			}
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
		}
		System.out.println(String.format("%s 行", listFile.size()));
		return listFile;
	}
}
